package com.wm.blog_admin.service;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wm.blog_admin.controller.req.AdminReq;
import com.wm.blog_admin.controller.resp.AdminExportResp;
import com.wm.blog_admin.controller.resp.BlogHomeResp;
import com.wm.blog_admin.controller.resp.HomeBarResp;
import com.wm.blog_admin.controller.resp.LoginResp;
import com.wm.blog_admin.dao.*;
import com.wm.blog_admin.domain.MailDo;
import com.wm.blog_admin.domain.WebScoketMsg;
import com.wm.blog_admin.event.MailEventPublisher;
import com.wm.blog_admin.event.WebSocketEventPublisher;
import com.wm.blog_admin.query.TAdminQuery;
import com.wm.blog_admin.query.TBlogQuery;
import com.wm.blog_admin.task.AdminThreadTask;
import com.wm.blog_common.base.AdminBase;
import com.wm.blog_common.base.BeanUtils;
import com.wm.blog_common.bean.PageHelper;
import com.wm.blog_common.bean.QueryPage;
import com.wm.blog_common.constatnt.CommonConstant;
import com.wm.blog_common.constatnt.ErrorConstant;
import com.wm.blog_common.constatnt.RegexConstant;
import com.wm.blog_common.domain.TAdminDO;
import com.wm.blog_common.domain.TBlogDO;
import com.wm.blog_common.entity.*;
import com.wm.blog_common.enums.DeleteFlag;
import com.wm.blog_common.enums.PublishFlag;
import com.wm.blog_common.enums.WeekNameFlag;
import com.wm.blog_common.exception.BusinessException;
import com.wm.blog_common.result.Result;
import com.wm.blog_common.util.*;
import com.wm.blog_common.util.excel.ExcelUtil;
import com.wm.blog_config.config.MailProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

/**
 * <p>
 * 管理员表 服务实现类
 * </p>
 *
 * @author wm_yu
 * @since 2020-03-24
 */
@Service
@Slf4j
public class TAdminService {
    @Autowired
    private TAdminDAO tAdminDAO;

    @Autowired
    private TAdminRoleDAO tAdminRoleDAO;

    @Autowired
    private TMenuService tMenuService;

    @Autowired
    private TUserDAO tUserDAO;

    @Autowired
    private TBlogDAO tBlogDAO;

    @Autowired
    private TFeedbackDAO tFeedbackDAO;

    @Autowired
    private WebSocketEventPublisher webSocketEventPublisher;

    @Autowired
    private MailProperties mailProperties;

    @Autowired
    private SendEmailService sendEmailService;

    @Autowired
    private MailEventPublisher mailEventPublisher;

    @Autowired
    private ThreadPoolTaskExecutor poolTaskExecutor;

    /**
     * 根据ID查询
     * @param id
     * @return
     */
    public Result<TAdminDO> selectById(Long id){
        return Result.success(BeanUtils.copyProperties(tAdminDAO.getById(id), TAdminDO.class));
    }

    /**
    * 根据ID删除
    * @param id
    * @return
    */
    public Result deleteById(Long id){
        return tAdminDAO.removeById(id)? Result.success(): Result.failure();
    }

    /**
    * 添加
    * @param tAdmin
    * @return
    */
    public Result insert(TAdmin tAdmin){
        return tAdminDAO.save(tAdmin)? Result.success(): Result.failure();
    }

    /**
    * 修改
    * @param tAdmin
    * @return
    */
    public Result update(TAdmin tAdmin){
        return tAdminDAO.updateById(tAdmin)? Result.success(): Result.failure();
    }

    /**
    * 统计总数
    *
    * @param query
    * @return
    */
    public Result<Integer> count(TAdminQuery query) {
        return Result.success(tAdminDAO.count(this.combineQuery(query)));
    }

    /**
    * 列表查询
    * @param query
    * @return
    */
    public Result<List<TAdminDO>> list(TAdminQuery query){
        return Result.success(BeanUtils.copyListProperties(tAdminDAO.list(this.combineQuery(query)), TAdminDO.class));
    }
    /**
    * 分页查询
    * @param page
    * @return
    */
    public Result<Page<TAdminDO>> page(QueryPage page, TAdminQuery query){
        return Result.success(PageHelper.newPage(tAdminDAO.page(page,this.combineQuery(query)), TAdminDO.class));
    }

    /**
     * 组装查询条件
     *
     * @param query
     * @return
     */
    private QueryWrapper<TAdmin> combineQuery(TAdminQuery query) {
        QueryWrapper<TAdmin> wrapper = new QueryWrapper<>();
        Optional.ofNullable(query).ifPresent(x -> {
            Optional.ofNullable(x.getPassword()).filter(org.apache.commons.lang3.StringUtils::isNotEmpty).ifPresent(y -> {
                wrapper.eq("pass_word",y);
            });
            Optional.ofNullable(x.getUsername()).filter(org.apache.commons.lang3.StringUtils::isNotEmpty).ifPresent(y -> {
                wrapper.eq("user_name",y);
            });
            Optional.ofNullable(x.getName()).filter(org.apache.commons.lang3.StringUtils::isNotEmpty).ifPresent(y -> {
                wrapper.like("user_name",y);
            });
            Optional.ofNullable(x.getMobile()).filter(org.apache.commons.lang3.StringUtils::isNotEmpty).ifPresent(y -> {
                wrapper.like("mobile",y);
            });
            Optional.ofNullable(x.getEmail()).filter(org.apache.commons.lang3.StringUtils::isNotEmpty).ifPresent(y -> {
                wrapper.like("email",y);
            });
            Optional.ofNullable(x.getStatus()).ifPresent(y -> {
                wrapper.eq("status",y);
            });
        });
        return wrapper;
    }


    /**
     * 绑定角色,修改角色
     * @param query
     * @return
     */
    public Result bindRole(TAdminQuery query) {
        query = Optional.ofNullable(query).orElse(new TAdminQuery());
        if(ObjectUtils.isEmpty(query.getRoleIdList())){
            return Result.success("角色id数组为空");
        }
        if(ObjectUtils.isEmpty(query.getAdminId())){
            return Result.failure("用户id为空");
        }
        //删除用户的所有角色
        QueryWrapper<TAdminRole> userRoleQueryWrapper = new QueryWrapper<>();
        userRoleQueryWrapper.eq("admin_id",query.getAdminId());
        tAdminRoleDAO.remove(userRoleQueryWrapper);
        //重新绑定角色
        final Long userId = query.getAdminId();
        List<TAdminRole> list = query.getRoleIdList()
                .stream()
                .map(x -> {
                    TAdminRole userRole = new TAdminRole();
                    userRole.setRoleId(x);
                    userRole.setAdminId(userId);
                    return userRole;
                })
                .collect(Collectors.toList());
        tAdminRoleDAO.saveBatch(list);
        return Result.success();
    }

    /**
     * 用户登录操作
     * @param query
     * @return
     */

    //登录接口已集成到spring security中,配合gateway网关使用
    @Deprecated
    public Result login(TAdminQuery query) {
        query = Optional.ofNullable(query).orElse(new TAdminQuery());
        if(StringUtils.isEmpty(query.getUsername()) ||StringUtils.isEmpty(query.getPassword())){
            return Result.failure(ErrorConstant.USER_PW_ACCOUNT_EMPTY);
        }
        //登录
        QueryWrapper<TAdmin> wrapper = this.combineQuery(query);
        TAdmin admin = Optional.ofNullable(tAdminDAO.getOne(wrapper)).orElse(new TAdmin());
        if(ObjectUtils.isEmpty(admin.getId())){
            return Result.failure(ErrorConstant.USER_PW_ACCOUNT_ERROR);
        }
        LoginResp resp = BeanUtils.copyProperties(admin, LoginResp.class);
        resp.setToken(CommonUtil.createToken());
        //返回token
        return Result.success(resp);
    }


    /**
     * 通过username查询管理员信息
     * @param username
     * @return
     */
    public Result findByUserName(String username) {
        if(StringUtils.isEmpty(username)){
            return Result.failure(ErrorConstant.ADMIN_USERNAME_EMPTY);
        }
        TAdminQuery query = new TAdminQuery();
        query.setUsername(username);
        QueryWrapper<TAdmin> wrapper = this.combineQuery(query);
        TAdmin admin = Optional.ofNullable(tAdminDAO.getOne(wrapper)).orElse(new TAdmin());
        return Result.success(BeanUtils.copyProperties(admin, AdminBase.class));
    }


    /**
     * 获取当前登录人信息
     * @param adminId
     * @return
     */
    public Result getCurrent(Long adminId) {
        if(-1 == adminId){
            return Result.success();
        }
        TAdmin admin = Optional
                .ofNullable(tAdminDAO.getById(adminId))
                .orElse(new TAdmin());
        return Result.success(admin);
    }

    /**
     * 用户首页加载数据   加载该管理员下的数据
     *
     * @return
     */
    public Result infoCardData(Long adminId) {
        if (ObjectUtils.isEmpty(adminId)) {
            return Result.failure(ErrorConstant.ADMIN_ID_EMPTY);
        }
        /**
         * 本月用户新增数
         * 用户累计数
         * 用户反馈量
         * 用户点击量
         * 本月用户发布博文量
         * 累计发布博文量
         */
        int userCount = tUserDAO.count();
        //本月用户用户数
        QueryWrapper<TUser> wrapper = new QueryWrapper<>();
        wrapper.apply("DATE_FORMAT(create_time, '%Y%m') = DATE_FORMAT(CURDATE(), '%Y%m')");
        int monthUserCount = tUserDAO.count(wrapper);
        //用户反馈量 该admin下
        QueryWrapper<TFeedback> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("admin_id", adminId);
        int feedCount = tFeedbackDAO.count(queryWrapper);
        //用户点击量
        TBlogQuery blogQuery = new TBlogQuery();
        blogQuery.setIsPublish(PublishFlag.PUBLISH.getValue());
        int clickCount = tBlogDAO.clickCount(blogQuery);
        //用户累计发布博文数
        QueryWrapper<TBlog> blogQueryWrapper = new QueryWrapper<>();
        blogQueryWrapper.eq("admin_id", adminId);
        int blogCount = tBlogDAO.count(blogQueryWrapper);
        blogQueryWrapper.apply("DATE_FORMAT(create_time, '%Y%m') = DATE_FORMAT(CURDATE(), '%Y%m')");
        int monthBlogCount = tBlogDAO.count(blogQueryWrapper);
        List<BlogHomeResp> respList = this.buildHomeList(userCount, feedCount, monthUserCount, clickCount, blogCount, monthBlogCount);

        //推送消息 todo
        webSocketEventPublisher.publish(new WebScoketMsg(){{
            setMsg("测试");
        }});
        return Result.success(respList);
    }

    private List<BlogHomeResp> buildHomeList(int userCount, int feedCount, int monthUserCount, int clickCount, int blogCount, int monthBlogCount) {
        /**
         * 初始化前端需要的数据
         */
        String s = "[{ title: '本月新增用户', icon: 'md-share', count: 657, color: '#ed3f14' }," +
                "{ title: '累计用户量', icon: 'md-person-add', count: 803, color: '#2d8cf0' }," +
                "{ title: '用户反馈量', icon: 'md-locate', count: 232, color: '#19be6b' }," +
                "{ title: '累计点击量', icon: 'md-locate', count: 232, color: '#19be6b' }," +
                "{ title: '本月发布博文', icon: 'md-chatbubbles', count: 12, color: '#E46CBB' }," +
                "{ title: '累计发布博客', icon: 'md-help-circle', count: 142, color: '#ff9900' }]";
        List<BlogHomeResp> respList = JSONObject.parseArray(s, BlogHomeResp.class);
        respList.forEach(x -> {
            String title = x.getTitle();
            switch (title) {
                case "本月新增用户":
                    x.setCount(monthUserCount);
                    break;
                case "累计用户量":
                    x.setCount(userCount);
                    break;
                case "用户反馈量":
                    x.setCount(feedCount);
                    break;
                case "累计点击量":
                    x.setCount(clickCount);
                    break;
                case "本月发布博文":
                    x.setCount(monthBlogCount);
                    break;
                case "累计发布博客":
                    x.setCount(blogCount);
                    break;
                default:
                    break;
            }
        });
        return respList;
    }

    /**
     * 用户每周活跃数据
     *
     * @param adminId
     * @return
     */
    public Result weekActive(Long adminId) {
        if (ObjectUtils.isEmpty(adminId)) {
            return Result.failure(ErrorConstant.ADMIN_ID_EMPTY);
        }
        List<Date> dateList = DateUtil.todayWeekList();
        TBlogQuery query = new TBlogQuery();
        query.setStartCreateTime(dateList.get(0));
        query.setEndCreateTime(dateList.get(1));
        Result<List<TBlogDO>> result = tBlogDAO.weekActive(query);
        HomeBarResp homeBarResp = new HomeBarResp();
        if (result.isSuccess() && !CollectionUtils.isEmpty(result.getData())) {
            //处理返回数据,没有的数据填充0
            List<TBlogDO> dataList = result.getData();
            //时间排序
            List<TBlogDO> sortList = dataList
                    .stream()
                    .sorted(Comparator.comparing(TBlogDO::getCreateDate))
                    .collect(Collectors.toList());
            //构建已有的数据map
            Map<Integer, TBlogDO> map = sortList
                    .stream()
                    .filter(x -> !ObjectUtils.isEmpty(x) && !ObjectUtils.isEmpty(x.getCreateDate()))
                    .collect(Collectors
                            .toMap(x -> DateUtil.getWeekDayAboutLocalTime(DateUtil.dateToLocalDateTime(x.getCreateDate())), v -> v));
            int maxWeek = DateUtil.getWeekDayAboutLocalTime(DateUtil.dateToLocalDateTime(sortList.get(sortList.size() - 1).getCreateDate()));
            for (int i = 1; i <= maxWeek; i++) {
                TBlogDO blogDO = map.getOrDefault(i, new TBlogDO());
                switch (i) {
                    case 1:
                        homeBarResp.setMon(WeekNameFlag.getText(i));
                        homeBarResp.setMonBlogCount(blogDO.getBlogCount());
                        break;
                    case 2:
                        homeBarResp.setTue(WeekNameFlag.getText(i));
                        homeBarResp.setTueBlogCount(blogDO.getBlogCount());
                        break;
                    case 3:
                        homeBarResp.setWed(WeekNameFlag.getText(i));
                        homeBarResp.setWedBlogCount(blogDO.getBlogCount());
                        break;
                    case 4:
                        homeBarResp.setThu(WeekNameFlag.getText(i));
                        homeBarResp.setThuBlogCount(blogDO.getBlogCount());
                        break;
                    case 5:
                        homeBarResp.setFriBlogCount(blogDO.getBlogCount());
                        homeBarResp.setFri(WeekNameFlag.getText(i));
                        break;
                    case 6:
                        homeBarResp.setSatBlogCount(blogDO.getBlogCount());
                        homeBarResp.setSat(WeekNameFlag.getText(i));
                        break;
                    case 7:
                        homeBarResp.setSunBlogCount(blogDO.getBlogCount());
                        homeBarResp.setSun(WeekNameFlag.getText(i));
                        break;
                    default:
                        break;
                }
            }
        }
        return Result.success(homeBarResp);
    }


    public Result editPassword(TAdminQuery query) {
        Result<String> validate = ObjectValidateUtil.validate(query);
        if(!validate.isSuccess()){
            return validate;
        }
        if(org.apache.commons.lang3.StringUtils.equals(query.getOldPassword(),query.getPassword())){
            return Result.failure(ErrorConstant.OLD_NEW_PASSWORD_SAME);
        }
        if(!org.apache.commons.lang3.StringUtils.equals(query.getPassword(),query.getConfirmPw())){
            return Result.failure(ErrorConstant.PW_CONFIRM_ERROR);
        }
        //校验密码
        TAdmin admin = Optional.ofNullable(tAdminDAO.getById(query.getAdminId())).orElse(new TAdmin());
        if(ObjectUtils.isEmpty(admin.getId()) || !org.apache.commons.lang3.StringUtils.equals(query.getOldPassword(),admin.getPassWord())){
            return Result.failure(ErrorConstant.OLD_PASSWORD_ERROR);
        }
        admin.setUpdateTime(DateUtil.getCurrentDate());
        admin.setPassWord(query.getPassword());
        return tAdminDAO.updateById(admin) ? Result.success(): Result.failure();
    }

    public Result addAdmin(TAdminQuery query, HttpServletRequest request) {
        Optional.ofNullable(query.getUserName()).orElseThrow(() -> new BusinessException(ErrorConstant.ADMIN_USERNAME_EMPTY));
        Optional.ofNullable(query.getEmail()).orElseThrow(() -> new BusinessException(ErrorConstant.USER_EMAIL_EMPTY));
        if(!RegexUitl.check(query.getMobile(), RegexConstant.MOBLIE_REGEX)){
            return Result.failure(ErrorConstant.MOBLIE_ILLEGAL);
        }
        //校验重名
        QueryWrapper<TAdmin> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name",query.getUserName());
        wrapper.last("limit 1");
        TAdmin admin = Optional.ofNullable(tAdminDAO.getOne(wrapper)).orElse(new TAdmin());
        if(!ObjectUtils.isEmpty(admin.getId())){
            return Result.failure(ErrorConstant.USER_NAME_EXSIT);
        }
        //校验邮箱
        QueryWrapper<TAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email",query.getEmail());
        queryWrapper.last("limit 1");
        admin = Optional.ofNullable(tAdminDAO.getOne(queryWrapper)).orElse(new TAdmin());
        if(!ObjectUtils.isEmpty(admin.getId())){
            return Result.failure(ErrorConstant.USER_EMAIL_EXIST);
        }
        //添加账号
        Date now = DateUtil.getCurrentDate();
        BeanUtils.copyProperties(query,admin);
        admin.setUpdateTime(now);
        admin.setCreateTime(now);
        admin.setStatus(DeleteFlag.DISABLE.getValue());
        admin.setPassWord(CommonConstant.ACCOUNT_INIT_PASSWORD);
        boolean b = tAdminDAO.save(admin);
        if(b){
            //发送激活邮件
            String subject = String.format(CommonConstant.ACTIVE_ACCOUNT_EMAIL,query.getUserName());
            List<String> toList = new ArrayList<>();
            //构建模板参数
            Map<String, Object> map = new HashMap<>();
            String s = DateUtil.formatterLocalDateTimeToString(now, "yyyy-MM-dd HH:mm:ss");
            map.put("userName",query.getUserName());
            map.put("superEmail",mailProperties.getUsername());
            map.put("password", CommonConstant.ACCOUNT_INIT_PASSWORD);
            map.put("email",query.getEmail());
            map.put("registTime",s);
            map.put("ip", IpUtil.getIpAddress(request));
            map.put("currentTime",s);
            map.put("id",1L);
            map.put("url", CommonConstant.ACTIVE_ACCOUNT_URL);
            map.put("addresss","广东省深圳市");
            map.put("Authorization",query.getAuthorization());
            toList.add(query.getEmail());
            MailDo mailDo = MailDo
                    .builder()
                    .flag(true)
                    .from(mailProperties.getUsername())
                    .htmlName("activeAccount")
                    .paramsMap(map)
                    .subject(subject).toList(toList).build();
            mailEventPublisher.publish(mailDo);
            return Result.success();
        }
        return Result.failure();
    }

    /**
     * 测试邮件发送
     * @return
     */
    public Result testEmail() throws MessagingException {
        List<String> toList = new ArrayList<String>(){{
            add("1530267177@qq.com");
        }};
        sendEmailService.sendHtmlMail(toList,mailProperties.getUsername(),"账号激活","activeAccount.html",new HashMap<String,Object>(
        ){{
            put("userName","yuwangming");
        }});
        return Result.success();
    }


    /**
     * 账号激活
     * @param query
     * @return
     */
    public Result activeAccount(TAdminQuery query) {
        query = Optional.ofNullable(query).orElse(new TAdminQuery());
        Optional.ofNullable(query.getId()).orElseThrow(() -> new BusinessException(ErrorConstant.USER_ID_EMPTY));
        Optional.ofNullable(query.getEmail()).orElseThrow(() -> new BusinessException(ErrorConstant.USER_EMAIL_EMPTY));
        //查询当前用户
        TAdmin admin = Optional.ofNullable(tAdminDAO.getById(query.getId())).orElse(new TAdmin());
        if(ObjectUtils.isEmpty(admin.getId()) || !query.getEmail().equals(admin.getEmail())){
            //TODo 激活失败,发送失败邮件
            return Result.failure(ErrorConstant.USER_ERROR);
        }
        Date now = DateUtil.getCurrentDate();
        admin.setUpdateTime(now);
        admin.setStatus(DeleteFlag.ENABLE.getValue());
        boolean b = tAdminDAO.updateById(admin);
        if(b){
            //发送激活成功邮件
            String subject = String.format( CommonConstant.USER_ACTIVE_SUCCESS_EMAIL_SUBJECT,admin.getUserName());
            List<String> toList = new ArrayList<>();
            toList.add(query.getEmail());
            MailDo mailDo = MailDo
                    .builder()
                    .flag(false)
                    .from(mailProperties.getUsername())
                    .content(CommonConstant.USER_ACTIVE_SUCCESS_EMAIL_CONTENT)
                    .subject(subject).toList(toList).build();
            mailEventPublisher.publish(mailDo);
            return Result.success();
        }
        return Result.failure();
    }

    /**
     * 校验账号是否存在 存在返回true
     * @param userName
     * @return
     */
    private boolean checkUserNameExist(String userName) {
        if(StringUtils.isEmpty(userName)){
            return true;
        }
        QueryWrapper<TAdmin> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name",userName);
        wrapper.last("limit 1");
        TAdmin admin = Optional.ofNullable(tAdminDAO.getOne(wrapper)).orElse(new TAdmin());
        return !ObjectUtils.isEmpty(admin.getId());
    }

    /**
     * 校验邮箱是否存在 存在返回true
     * @param email
     * @return
     */
    private boolean checkEmailExist(String email) {
        if(StringUtils.isEmpty(email)){
            return true;
        }
        QueryWrapper<TAdmin> wrapper = new QueryWrapper<>();
        wrapper.eq("email",email);
        wrapper.last("limit 1");
        TAdmin admin = Optional.ofNullable(tAdminDAO.getOne(wrapper)).orElse(new TAdmin());
        return !ObjectUtils.isEmpty(admin.getId());
    }



    /**
     * 禁用账号
     * @param id
     * @param adminId
     * @return
     */
    public Result disableAccount(Long id, Long adminId) {
        Optional.ofNullable(id).orElseThrow(() -> new BusinessException(ErrorConstant.ADMIN_ID_EMPTY));
        //超级管理员不能禁用自身账号
        if(id.equals(adminId)){
            return Result.failure(ErrorConstant.ACCOUNT_NOT_PERSSION);
        }
        //校验是否为超级管理员 todo 暂时将管理员写死
        TAdmin admin = Optional.ofNullable(tAdminDAO.getById(adminId)).orElse(new TAdmin());
        if(!ObjectUtils.isEmpty(admin.getId())){
            if(!"superAdmin".equals(admin.getUserName())){
                return Result.failure(ErrorConstant.ACCOUNT_NOT_PERSSION);
            }
            Date now = DateUtil.getCurrentDate();
            TAdmin tAdmin = new TAdmin();
            tAdmin.setId(id);
            tAdmin.setStatus(DeleteFlag.DISABLE.getValue());
            tAdmin.setUpdateTime(now);
            return tAdminDAO.updateById(tAdmin) ? Result.success(): Result.failure();
        }
        return Result.failure();
    }

    public Result addSocket(String msg) {
        //推送消息 todo
        try {
            webSocketEventPublisher.publish(new WebScoketMsg(){{
                setMsg(msg);
            }});
        } catch (Exception e) {
            log.error("推送数据失败");
        }

        return Result.success();
    }

    /**
     * 超级管理员激活账号
     * @param query
     * @return
     */
    public Result adminActive(TAdminQuery query) {
        Optional.ofNullable(query.getId()).orElseThrow(() -> new BusinessException(ErrorConstant.ADMIN_ID_EMPTY));
        //只有超级管理员才能激活 todo 先写死
        TAdmin admin = Optional.ofNullable(tAdminDAO.getById(query.getAdminId())).orElse(new TAdmin());
        if(Objects.isNull(admin.getId()) || !"superAdmin".equals(admin.getUserName())){
            return Result.failure(ErrorConstant.ACCOUNT_NOT_PERSSION);
        }
        //校验当前账号是否处于激活状态
        TAdmin activeAdmin = Optional.ofNullable(tAdminDAO.getById(query.getId())).orElse(new TAdmin());
        if(Objects.isNull(activeAdmin.getId()) || DeleteFlag.ENABLE.getValue().equals(activeAdmin.getStatus())){
            return Result.failure(ErrorConstant.ACCOUNT_ACTIVE_ERROR);
        }
        //激活操作
        Date now = DateUtil.getCurrentDate();
        activeAdmin.setUpdateTime(now);
        activeAdmin.setStatus(DeleteFlag.ENABLE.getValue());
        return tAdminDAO.updateById(activeAdmin) ? Result.success():Result.failure();
    }

    /**
     * 导出excel文件
     * @param query
     * @param response
     */
    public void export(TAdminQuery query, HttpServletResponse response) {
//使用多线程查询
        Integer current = 1;
        Integer size = 1;
        QueryPage page = new QueryPage(current, size);
        Result<Page<TAdminDO>> result = this.page(page, query);
        if(result.isSuccess()){
            Long total = result.getData().getTotal();
            if(total > 0){
                //计算需要的线程数量
                Integer threadCount = CommonUtil.getThreadCount(total.intValue());
                List<Future<List<AdminExportResp>>> futureList = new ArrayList<>();
                for (Integer i = 1; i <= threadCount; i++) {
                    //构建多线程请求入参
                    Future<List<AdminExportResp>> future = poolTaskExecutor.submit(new AdminThreadTask(i, CommonConstant.DEFAULT_MAX_SIZE, this, query));
                    futureList.add(future);
                }
                //处理线程结果
                if(!CollectionUtils.isEmpty(futureList)){
                    List<AdminExportResp> respList = new ArrayList<>();
                    for (Future<List<AdminExportResp>> future : futureList) {
                        try {
                            respList.addAll(future.get());
                        } catch (InterruptedException | ExecutionException e) {
                            log.error("线程获取数据失败:[{}]",e.getMessage(),e);
                            //取消当前任务
                            future.cancel(true);
                        }
                    }
                    //导出excel
                    List<String> headerList = CommonUtil.getExcelHeaderList(AdminExportResp.class);
                    String title = CommonConstant.ADMIN_EXPORT_TITLE;
                    ExcelUtil.downloadExcelFile(title,headerList,respList,response);
                }
            }
        }

    }


    public Result editAdmin(AdminReq admin) {
        admin = Optional.ofNullable(admin).orElse(new AdminReq());
        Optional.ofNullable(admin.getId()).orElseThrow(() -> new BusinessException(ErrorConstant.ADMIN_ID_EMPTY));
        //邮箱合法校验
        if(StringUtil.isNotEmpty(admin.getEmail()) && !CommonValidUtil.checkEmail(admin.getEmail())){
            return Result.failure(ErrorConstant.USER_EMIAL_ILLEGAL);
        }
        //手机合法校验
        if(StringUtil.isNotEmpty(admin.getMobile()) && !CommonValidUtil.checkMobile(admin.getMobile())){
            return Result.failure(ErrorConstant.MOBILE_ILLEGAL);
        }
        //qq校验
        if(StringUtil.isNotEmpty(admin.getQqNumber()) && !CommonValidUtil.checkQQ(admin.getQqNumber())){
            return Result.failure(ErrorConstant.USER_QQ_NUMBER_ILLEGAL);
        }
        //手机号/微信号/qq号唯一性校验
        Result result = this.checkUniqueInfo(admin.getMobile(), admin.getQqNumber(), admin.getEmail(), admin.getId());
        if(!result.isSuccess()){
            return result;
        }
        if(StringUtil.isNotEmpty(admin.getBirthdayStr())){
            admin.setBirthday(DateUtil.localDateToDate(DateUtil.formatterStringToLocalDate(admin.getBirthdayStr(),DateUtil.DATE_PATTERN_STRING)));
        }
        Date now = DateUtil.getCurrentDate();
        admin.setUpdateTime(now);
        return tAdminDAO.updateById(admin) ? Result.success():Result.failure();
    }


    /**
     * 针对用户手机号,邮箱,电子邮箱唯一性校验
     * @param mobile 手机号
     * @param qqNumber qq号
     * @param email 邮箱
     * @return
     */
    private Result checkUniqueInfo(String mobile,String qqNumber,String email,Long id){
        if(StringUtil.isNotEmpty(mobile)){
            QueryWrapper<TAdmin> wrapper = new QueryWrapper<>();
            wrapper.ne("id",id);
            wrapper.eq("mobile",mobile);
            wrapper.last("limit 1");
            TAdmin admin = Optional.ofNullable(tAdminDAO.getOne(wrapper)).orElse(new TAdmin());
            if(!ObjectUtils.isEmpty(admin.getId())){
                return Result.failure(ErrorConstant.USER_MOBILE_EXIST);
            }
        }

        if(StringUtil.isNotEmpty(mobile)){
            QueryWrapper<TAdmin> wrapper = new QueryWrapper<>();
            wrapper.ne("id",id);
            wrapper.eq("qq_number",qqNumber);
            wrapper.last("limit 1");
            TAdmin admin = Optional.ofNullable(tAdminDAO.getOne(wrapper)).orElse(new TAdmin());
            if(!ObjectUtils.isEmpty(admin.getId())){
                return Result.failure(ErrorConstant.USER_QQ_EXIST);
            }
        }

        if(StringUtil.isNotEmpty(mobile)){
            QueryWrapper<TAdmin> wrapper = new QueryWrapper<>();
            wrapper.ne("id",id);
            wrapper.eq("email",email);
            wrapper.last("limit 1");
            TAdmin admin = Optional.ofNullable(tAdminDAO.getOne(wrapper)).orElse(new TAdmin());
            if(!ObjectUtils.isEmpty(admin.getId())){
                return Result.failure(ErrorConstant.USER_EMAIL_EXIST);
            }
        }
        return Result.success();
    }


}







